package com.nineclock.common.filter;

import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 *
 * 拦截所有的请求，进行过滤， 在线程中存储 用户和企业信息
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@WebFilter(value = "/*")
public class CurrentUserFilter extends GenericFilterBean{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        SecurityContextHolder.getContext(); //获取 security 上下文对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //anonymousUser: 如果没有登录， name是 anonymousUser（匿名用户）
        String name = authentication.getName();

        if(name != null && !"anonymousUser".equals(name)){
            UserInfo userInfo = JsonUtils.toBean(name, UserInfo.class);
            CurrentUserHolder.set(userInfo);
        }

        chain.doFilter(request, response);
    }
}
